// 兼容：从全局 Vue 实例或 window.__app__ 方式获取 store；如项目 main.js 已 export store，可直接 import
import Vue from 'vue'

let _store = null
function resolveStore () {
  if (_store) return _store
  // 方式1：通过 Vue 根实例
  if (Vue && Vue.prototype && Vue.prototype.$store) { _store = Vue.prototype.$store; return _store }
  // 方式2：window 注入（若 main.js 手动挂载）
  if (typeof window !== 'undefined' && window.__STORE__) { _store = window.__STORE__; return _store }
  // 方式3：动态 require（若循环依赖会失败则捕获）
  try {
    const m = require('@/store')
    _store = m.default || m.store || null
  } catch (e) { /* ignore */ }
  return _store
}

const permissionBitMap = {
  dept: 1 << 0,
  major: 1 << 1,
  class: 1 << 2,
  student: 1 << 3,
  teacher: 1 << 4,
  course: 1 << 5,
  selection: 1 << 6,
  admin: 1 << 7
}

export function isSuperAdminAccount () {
  const store = resolveStore()
  const username = store && store.state.user.userInfo ? store.state.user.userInfo.username : ''
  return username === 'admin'
}

export function isAdminEmptyPermissionFallback () {
  const store = resolveStore()
  if (!store) return false
  const { userType, permissions } = store.state.user
  return userType === 3 && (!permissions || permissions.length === 0)
}

export function getUserType () {
  const store = resolveStore()
  return store ? store.state.user.userType : null
}

export function getPermissions () {
  const store = resolveStore()
  return store ? store.state.user.permissions : []
}

export function hasStrict (perm) {
  const store = resolveStore()
  if (!store) return false
  if (isSuperAdminAccount()) return true
  const list = store.state.user.permissions || []
  return list.includes(perm)
}

export function hasBit (perm) {
  const store = resolveStore()
  if (!store) return false
  const bit = permissionBitMap[perm]
  if (!bit) return false
  return (store.state.user.permissionValue & bit) !== 0
}

export function getUserContext () {
  const store = resolveStore()
  const info = store && store.state.user.userInfo ? store.state.user.userInfo : {}
  return {
    userType: getUserType(),
    permissions: getPermissions(),
    username: info.username || '',
    isSuperAdmin: isSuperAdminAccount(),
    adminEmptyFallback: isAdminEmptyPermissionFallback()
  }
}